<template>
	<div class="company-info-container">
		<van-form @submit="onSubmit">
			<van-cell-group>
				<!-- 企业基本信息 -->
				<van-field
					v-model="form.pollutionSourceName"
					name="pollutionSourceName"
					label="企业名称"
					placeholder="请输入企业名称"
					:rules="[{ required: true, message: '企业名称必填' }]"
				/>

				<van-field
					v-model="form.creditCode"
					name="creditCode"
					label="统一社会信用代码"
					placeholder="请输入统一社会信用代码"
					:rules="[{ required: true, message: '统一社会信用代码必填' }]"
				/>

				<FormPopupSelect
					required
					label="行政区划"
					field-key="areaCode"
					v-model:value="form.areaCode"
					dic-key="AREA_CODE"
					field="text"
					@popup-confirm="onPopupConfirmAreaCode"
				/>

				<van-field
					v-model="form.address"
					name="address"
					label="企业地址"
					placeholder="请输入企业地址"
					:rules="[{ required: true, message: '企业地址必填' }]"
				/>

				<van-field
					v-model="form.legalPerson"
					name="legalPerson"
					label="法人代表"
					placeholder="请输入法人代表"
					:rules="[{ required: true, message: '法人代表必填' }]"
				/>

				<van-field
					v-model="form.legalPersonPhone"
					name="legalPersonPhone"
					label="法人联系电话"
					placeholder="请输入法人联系电话"
					:rules="[{ required: true, message: '法人联系电话必填' }]"
				/>

				<van-field
					v-model="form.linkman"
					name="linkman"
					label="环保负责人"
					placeholder="请输入环保负责人"
					:rules="[{ required: true, message: '环保负责人必填' }]"
				/>

				<van-field
					v-model="form.linkmanPhone"
					name="linkmanPhone"
					label="环保负责人电话"
					placeholder="请输入环保负责人电话"
					:rules="[{ required: true, message: '环保负责人联系电话必填' }]"
				/>
			</van-cell-group>

			<!-- 设备设施情况 -->
			<van-cell-group title="设备设施情况">
				<!-- 废水治理设施 -->
				<van-field name="existWateGovern" label="废水治理设施" :rules="[{ required: true, message: '废水治理设施必填' }]">
					<template #input>
						<van-radio-group v-model="form.existWateGovern" direction="horizontal">
							<van-radio name="1">是</van-radio>
							<van-radio name="0">否</van-radio>
						</van-radio-group>
					</template>
				</van-field>

				<!-- 废水排污口 -->
				<div v-if="form.existWateGovern === '1'" class="outlet-section">
					<Outlet v-model="form.waterOutlets" pollution-type="FS" @change="onWaterOutletsChange" />
				</div>

				<!-- 废气治理设施 -->
				<van-field name="existAirGovern" label="废气治理设施" :rules="[{ required: true, message: '废气治理设施必填' }]">
					<template #input>
						<van-radio-group v-model="form.existAirGovern" direction="horizontal">
							<van-radio name="1">是</van-radio>
							<van-radio name="0">否</van-radio>
						</van-radio-group>
					</template>
				</van-field>

				<!-- 废气排污口 -->
				<div v-if="form.existAirGovern === '1'" class="outlet-section">
					<Outlet v-model="form.airOutlets" pollution-type="FQ" @change="onAirOutletsChange" />
				</div>

				<!-- 固危废贮存场所 -->
				<van-field name="existHhwStorge" label="固危废贮存场所" :rules="[{ required: true, message: '固危废贮存场所必填' }]">
					<template #input>
						<van-radio-group v-model="form.existHhwStorge" direction="horizontal">
							<van-radio name="1">是</van-radio>
							<van-radio name="0">否</van-radio>
						</van-radio-group>
					</template>
				</van-field>

				<!-- 中水回用 -->
				<!-- <van-field name="existWateReuse" label="中水回用" :rules="[{ required: true, message: '中水回用必填' }]">
					<template #input>
						<van-radio-group v-model="form.existWateReuse" direction="horizontal">
							<van-radio name="1">是</van-radio>
							<van-radio name="0">否</van-radio>
						</van-radio-group>
					</template>
				</van-field> -->
			</van-cell-group>

			<!-- 提交按钮 -->
			<div class="submit-section">
				<van-button round block type="primary" native-type="submit" :loading="submitting"> 保存企业信息 </van-button>
			</div>
		</van-form>
	</div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { companyInfoApi } from '../../../api/company'
import Outlet from '../../../components/outlet'
import FormPopupSelect from '../../../components/form-popup-select'

export default {
	name: 'CompanyInfo',
	components: {
		Outlet,
		FormPopupSelect,
	},
	setup() {
		const router = useRouter()

		// 响应式数据
		const form = reactive({
			pollutionSourceName: '',
			creditCode: '',
			areaCode: '',
			address: '',
			legalPerson: '',
			legalPersonPhone: '',
			linkman: '',
			linkmanPhone: '',
			existAirGovern: '',
			existWateGovern: '',
			existHhwStorge: '',
			existWateReuse: '',
			outlets: [],
			waterOutlets: [],
			airOutlets: [],
		})

		const submitting = ref(false)

		// 初始化数据
		const initData = async () => {
			try {
				const res = await companyInfoApi.getCompanyInfo()
				if (res.code === '0' && res.data) {
					Object.assign(form, res.data)

					// 分离废水和废气排污口
					if (res.data.outlets) {
						form.waterOutlets = res.data.outlets.filter((o) => o.pollutionType === 'FS')
						form.airOutlets = res.data.outlets.filter((o) => o.pollutionType === 'FQ')
					}
				}
			} catch (error) {
				console.error('获取企业信息失败:', error)
				showToast('获取企业信息失败')
			}
		}

		// 行政区划选择确认
		const onPopupConfirmAreaCode = (data) => {
			console.log('选择的行政区划:', data.option, '显示文本:', data.text)
			// 由于使用了 v-model，这里不需要手动赋值
			// form.areaCode 会自动更新
		}

		// 废水排污口变化处理
		const onWaterOutletsChange = (outlets) => {
			form.waterOutlets = outlets
		}

		// 废气排污口变化处理
		const onAirOutletsChange = (outlets) => {
			form.airOutlets = outlets
		}

		// 提交表单
		const onSubmit = async (values) => {
			try {
				submitting.value = true

				// 验证排污口
				if (form.existWateGovern === '1' && form.waterOutlets.length === 0) {
					showToast('请填写废水治理设施因子')
					return
				}

				if (form.existAirGovern === '1' && form.airOutlets.length === 0) {
					showToast('请填写废气治理设施因子')
					return
				}

				// 合并排污口数据
				form.outlets = [...form.waterOutlets, ...form.airOutlets]

				const res = await companyInfoApi.updateCompanyInfo(form)

				if (res.code === '0') {
					showToast('保存成功')
					// 可以选择返回上一页或刷新数据
					setTimeout(() => {
						router.back()
					}, 1500)
				} else {
					showToast(res.msg || '保存失败')
				}
			} catch (error) {
				console.error('保存企业信息失败:', error)
				showToast(error.message || '保存失败')
			} finally {
				submitting.value = false
			}
		}

		// 页面加载时初始化
		onMounted(() => {
			initData()
		})

		return {
			form,
			submitting,
			onPopupConfirmAreaCode,
			onWaterOutletsChange,
			onAirOutletsChange,
			onSubmit,
		}
	},
}
</script>

<style lang="less" scoped>
.company-info-container {
	background-color: #f7f8fa;
	min-height: 100vh;

	.submit-section {
		margin: 16px;
	}

	.outlet-section {
		padding: 0;
		margin: 0;
	}
}

:deep(.van-cell-group__title) {
	padding-left: 16px;
	padding-right: 16px;
}

:deep(.van-field__label) {
	width: 100px;
}

:deep(.van-radio-group) {
	.van-radio {
		margin-right: 20px;
	}
}
</style>